package jack.com.servicekeep.utils;

import android.Manifest;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.Executors;

import jack.com.servicekeep.R;
import jack.com.servicekeep.service.MyAccessibilityService;

import static android.content.ContentValues.TAG;
import static android.content.Context.AUDIO_SERVICE;
import static android.content.Context.INPUT_METHOD_SERVICE;

public class AppUtil {

    /*
     * Function  :   发送Post请求到服务器
     * Param     :   params请求体内容，encode编码格式
     */
    public static void upload(final String strUrlPath, final String params) {
        Executors.newSingleThreadExecutor().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    byte[] data = URLEncoder.encode(params, "UTF-8").getBytes();//获得请求体
                    URL url = new URL(strUrlPath);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setConnectTimeout(5000);     //设置连接超时时间
                    httpURLConnection.setDoInput(true);                  //打开输入流，以便从服务器获取数据
                    httpURLConnection.setDoOutput(true);                 //打开输出流，以便向服务器提交数据
                    httpURLConnection.setRequestMethod("POST");     //设置以Post方式提交数据
                    httpURLConnection.setUseCaches(false);               //使用Post方式不能使用缓存
                    //设置请求体的类型是文本类型
                    httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                    //设置请求体的长度
                    httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
                    //获得输出流，向服务器写入数据
                    OutputStream outputStream = httpURLConnection.getOutputStream();
                    outputStream.write(data);
                    outputStream.flush();
                    outputStream.close();
                    int response = httpURLConnection.getResponseCode();            //获得服务器的响应码
                    Log.i("Drake", "response: ``````````````" + response);
                    if (response == HttpURLConnection.HTTP_OK) {

                    }
                    httpURLConnection.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static int register(final String strUrlPath, final String params) {
        try {
            byte[] data = URLEncoder.encode(params, "UTF-8").getBytes();//获得请求体
            URL url = new URL(strUrlPath);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(5000);     //设置连接超时时间
            httpURLConnection.setDoInput(true);                  //打开输入流，以便从服务器获取数据
            httpURLConnection.setDoOutput(true);                 //打开输出流，以便向服务器提交数据
            httpURLConnection.setRequestMethod("POST");     //设置以Post方式提交数据
            httpURLConnection.setUseCaches(false);               //使用Post方式不能使用缓存
            //设置请求体的类型是文本类型
            httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            //设置请求体的长度
            httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
            //获得输出流，向服务器写入数据
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(data);
            outputStream.flush();
            outputStream.close();
            int response = httpURLConnection.getResponseCode();            //获得服务器的响应码
            Log.i("Drake", "register response: ``````````````" + response);
            if (response == HttpURLConnection.HTTP_OK) {

            }
            httpURLConnection.disconnect();
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return -1;
    }


    public static String heartbeat2(String phoneId, int state, String phoneNumber, int battery, int phoneState) {

        StringBuffer buffer = new StringBuffer();
        try {
            StringBuilder request = new StringBuilder();
            request.append("http://sitong.zbbang.cn/heart.go/?");
            request.append("phoneId="+phoneId);
            request.append("&state="+state);
            request.append("&secretKey=YUEksdi6775KNs94STNBXk32");
            request.append("&phoneNumber="+phoneNumber);
            request.append("&battery="+battery);
            request.append("&phoneState="+phoneState);

            Log.d("yanjun", "request : " + request);

            URL url = new URL(request.toString());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();//开启连接
            connection.connect();//连接服务器

            if (connection.getResponseCode() == 200) {
                //使用字符流形式进行回复
                InputStream is = connection.getInputStream();
                //读取信息BufferReader
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String readLine = "";
                while ((readLine = reader.readLine()) != null) {
                    buffer.append(readLine);
                }
                is.close();
                reader.close();
                connection.disconnect();

                Log.d("Msg", buffer.toString());

            } else {
                Log.d("TAG", "ERROR CONNECTED");
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }


    public static void heartbeat(final String strUrlPath, final String params) {
        try {
            byte[] data = URLEncoder.encode(params, "UTF-8").getBytes();//获得请求体
            URL url = new URL(strUrlPath);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(5000);     //设置连接超时时间
            httpURLConnection.setDoInput(true);                  //打开输入流，以便从服务器获取数据
            httpURLConnection.setDoOutput(true);                 //打开输出流，以便向服务器提交数据
            httpURLConnection.setRequestMethod("GET");     //设置以Post方式提交数据
//            httpURLConnection.setUseCaches(true);               //使用Post方式不能使用缓存
            //设置请求体的类型是文本类型
            httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            //设置请求体的长度
            httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
            //获得输出流，向服务器写入数据
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(data);
            outputStream.flush();
            outputStream.close();
            int response = httpURLConnection.getResponseCode();            //获得服务器的响应码
            Log.d("AppUtil", "heartbeat response: ``````````````" + response);
            if (response == HttpURLConnection.HTTP_OK) {

            }
            httpURLConnection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getBuildInfo() {
//这里选用了几个不会随系统更新而改变的值
        StringBuffer buildSB = new StringBuffer();
        buildSB.append(Build.BRAND).append("/");
        buildSB.append(Build.PRODUCT).append("/");
        buildSB.append(Build.DEVICE).append("/");
        buildSB.append(Build.ID).append("/");
        buildSB.append(Build.VERSION.INCREMENTAL);
        return buildSB.toString();
// return Build.FINGERPRINT;
    }

    public static String getNotice(String phoneId) {

        StringBuffer buffer = new StringBuffer();

        try {
            StringBuilder request = new StringBuilder();
            request.append("http://sitong.zbbang.cn/getStuByPhoneID?");
            request.append("phoneID="+phoneId);

            URL url = new URL(request.toString());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();//开启连接
            connection.connect();//连接服务器

            if (connection.getResponseCode() == 200) {
                //使用字符流形式进行回复
                InputStream is = connection.getInputStream();
                //读取信息BufferReader
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String readLine = "";
                while ((readLine = reader.readLine()) != null) {
                    buffer.append(readLine);
                }
                is.close();
                reader.close();
                connection.disconnect();

                Log.d("Msg", buffer.toString());

            } else {
                Log.d("TAG", "ERROR CONNECTED");
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    public static String getUnlockCode(String phoneNumber, String phoneId) {

        StringBuffer buffer = new StringBuffer();

        try {
            StringBuilder request = new StringBuilder();
            request.append("http://sitong.zbbang.cn/autoUnlock?");
            request.append("phoneNumber="+phoneNumber);
            request.append("&phoneId="+phoneId);

            URL url = new URL(request.toString());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();//开启连接
            connection.connect();//连接服务器

            if (connection.getResponseCode() == 200) {
                //使用字符流形式进行回复
                InputStream is = connection.getInputStream();
                //读取信息BufferReader
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String readLine = "";
                while ((readLine = reader.readLine()) != null) {
                    buffer.append(readLine);
                }
                is.close();
                reader.close();
                connection.disconnect();

                Log.d("Msg", buffer.toString());

            } else {
                Log.d("TAG", "ERROR CONNECTED");
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    public static String getPhoneNumber(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            Log.d("yanjun", "checkSelfPermission true..." + tm.getLine1Number());
            return "";
        }
        Log.d("yanjun", "checkSelfPermission false..." + tm.getLine1Number());
        return tm.getLine1Number() == null ? "" : tm.getLine1Number();
    }

    public static String sendSmsMessage(String phoneId, String msg) {

        StringBuffer buffer = new StringBuffer();

        try {
            StringBuilder address = new StringBuilder();
            address.append("http://sitong.zbbang.cn/addSms?");

            URL url = new URL(address.toString());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();//开启连接
            connection.setRequestMethod("POST");
            connection.connect();//连接服务器

            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            String content = "phoneID=" + phoneId + "&content="+ URLEncoder.encode(msg, "utf-8");
            out.writeBytes(content);

            out.flush();
            out.close();

            if (connection.getResponseCode() == 200) {
                //使用字符流形式进行回复
                InputStream is = connection.getInputStream();
                //读取信息BufferReader
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String readLine = "";
                while ((readLine = reader.readLine()) != null) {
                    buffer.append(readLine);
                }
                is.close();
                reader.close();
                connection.disconnect();

                Log.d("Msg", buffer.toString());

            } else {
                Log.d("TAG", "ERROR CONNECTED");
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    public static String getDeviceUUID(Context context) {
        String uuid = loadDeviceUUID(context);
        if (TextUtils.isEmpty(uuid)) {
            uuid = getShortUuid22();
            saveDeviceUUID(context, uuid);
        }
        return uuid;
    }

    public static String getAndroidId(Context context) {
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }

    public static String buildDeviceUUID(Context context) {
        String androidId = getAndroidId(context);
        if ("9774d56d682e549c".equals(androidId)) {
            Random random = new Random();
            androidId = Integer.toHexString(random.nextInt())
                    + Integer.toHexString(random.nextInt())
                    + Integer.toHexString(random.nextInt());
        }

        return new UUID(androidId.hashCode(), getBuildInfo().hashCode()).toString();
    }

    public static String[] chars2 = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
            "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8",
            "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
            "U", "V", "W", "X", "Y", "Z" };

    public static String getShortUuid8() {
        StringBuffer shortBuffer = new StringBuffer();

        String uuid = UUID.randomUUID().toString().replace("-", "");
        Log.d("yanjun", "uuid="+uuid);
        for (int i = 0; i < 8; i++) {
            Log.d("yanjun", "i="+i);
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(chars2[x % 0x3E]);
        }
        return shortBuffer.toString();
    }

    private static final String[] chars = {
            "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
            "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
            "u", "v", "w", "x", "y", "z", "A", "B", "C", "D",
            "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
            "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
            "Y", "Z", "a1", "a2"
    };

    // 生成UUID
    public static String getShortUuid22() {
        StringBuilder sb = new StringBuilder();
        String uid = UUID.randomUUID().toString().replaceAll("-", "");
        int length = uid.length();
        // 将16进制数转换成64进制数
        // 2的4次方转化成2的6次方的数据
        // bcb da5 f41 172 4bc 28b 920 b1c 5f4 422 6e
        // 3位转2位
        int i = 0;
        for (; i < length; i = i + 3) {
            // 16进制数转化成10进制数
            int end = i + 3;
            if (end >= length) {
                end = length;
            }
            int t = Integer.parseInt(uid.substring(i, end), 16);
            // 10进制数转化成64进制数
            sb.append(chars[t / 64]);// 第一个数据
            sb.append(chars[t % 64]);// 第二个数据
        }
        return sb.toString();
    }

    private static String loadDeviceUUID(Context context) {
        return context.getSharedPreferences("device_uuid", Context.MODE_PRIVATE)
                .getString("uuid", null);
    }

    private static void saveDeviceUUID(Context context, String uuid) {
        context.getSharedPreferences("device_uuid", Context.MODE_PRIVATE)
                .edit()
                .putString("uuid", uuid)
                .apply();
    }

    public static String getPhoneNumber2(Context context){
        String phoneNumber = context.getSharedPreferences("device_uuid", Context.MODE_PRIVATE)
                .getString("phoneNumber", "");

        if(phoneNumber.isEmpty()){
            phoneNumber = getPhoneNumber(context);
            if(!phoneNumber.isEmpty()){
                savePhoneNumber(context, phoneNumber);
            }
        }
        return phoneNumber;
    }

    public static void savePhoneNumber(Context context, String phoneNumber) {
        context.getSharedPreferences("device_uuid", Context.MODE_PRIVATE)
                .edit()
                .putString("phoneNumber", phoneNumber)
                .apply();
    }


    //获取钉自学状态  0: 未激活  1:已激活  2:已退订
    public static int getDingState(Context context) {
        return context.getSharedPreferences("ding_state", Context.MODE_PRIVATE)
                .getInt("state", 0);
    }

    public static void saveDingState(Context context, int state) {
        context.getSharedPreferences("ding_state", Context.MODE_PRIVATE)
                .edit()
                .putInt("state", state)
                .apply();
    }

    //获取钉自学状态  0: 未激活  1:已激活  2:已退订
    public static int getCancelIsReport(Context context) {
        return context.getSharedPreferences("ding_state", Context.MODE_PRIVATE)
                .getInt("cancel_reported", 0);
    }

    public static void cancelReported(Context context) {
        context.getSharedPreferences("ding_state", Context.MODE_PRIVATE)
                .edit()
                .putInt("cancel_reported", 1)
                .apply();
    }

    //是否进行打卡  0: 不打卡， 1: 打卡
    public static int getPunchClockState(Context context) {
        return context.getSharedPreferences("ding_state", Context.MODE_PRIVATE)
                .getInt("punch_clock_state", 0);
    }

    public static void setPunchClockState(Context context, int state) {
        context.getSharedPreferences("ding_state", Context.MODE_PRIVATE)
                .edit()
                .putInt("punch_clock_state", state)
                .apply();
    }

    //是否再次执行进入钉钉  0: 不执行， 1: 执行
    public static int getAutoEnterDingFlag(Context context) {
        return context.getSharedPreferences("ding_state", Context.MODE_PRIVATE)
                .getInt("auto_enter_ding_flag", 0);
    }

    public static void setAutoEnterDingFlag(Context context, int state) {
        context.getSharedPreferences("ding_state", Context.MODE_PRIVATE)
                .edit()
                .putInt("auto_enter_ding_flag", state)
                .apply();
    }

    //获取清除缓存日期
    public static boolean isNeedCleanDingDate(Context context){
        String curDate = getDateString();
        if(curDate.equals(getCleanDateState(context))){
            return false;
        }else {
            return true;
        }
    }

    public static String getCleanDateState(Context context) {
        return context.getSharedPreferences("ding_state", Context.MODE_PRIVATE)
                .getString("ding_clean", "");
    }

    public static void setCleanDateState(Context context, String date) {
        context.getSharedPreferences("ding_state", Context.MODE_PRIVATE)
                .edit()
                .putString("ding_clean", date)
                .apply();
    }

    public static String getDateString(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        return simpleDateFormat.format(date);
    }

    //获取是否需要更新钉钉
    public static boolean getAllowLearnState(Context context) {
        return context.getSharedPreferences("ding_state", Context.MODE_PRIVATE)
                .getBoolean("allow_learn_state", true);
    }

    public static void setAllowLearnState(Context context, boolean flag) {
        context.getSharedPreferences("ding_state", Context.MODE_PRIVATE)
                .edit()
                .putBoolean("allow_learn_state", flag)
                .apply();
    }

    public static int getUpdateDingState(Context context) {
        return context.getSharedPreferences("ding_state", Context.MODE_PRIVATE)
                .getInt("update_ding", 0);
    }

    public static void setUpdateDingState(Context context, int flag) {
        context.getSharedPreferences("ding_state", Context.MODE_PRIVATE)
                .edit()
                .putInt("update_ding", flag)
                .apply();
    }

    public static int getMenuState(Context context) {
        return context.getSharedPreferences("ding_state", Context.MODE_PRIVATE)
                .getInt("menu_", 0);
    }

    public static void setMenuState(Context context, int flag) {
        context.getSharedPreferences("ding_state", Context.MODE_PRIVATE)
                .edit()
                .putInt("menu_", flag)
                .apply();
    }

    public static String getCourseCode(Context context) {
        return context.getSharedPreferences("ding_state", Context.MODE_PRIVATE)
                .getString("course_code", "#00");
    }

    public static void setCourseCode(Context context, String  code) {
        context.getSharedPreferences("ding_state", Context.MODE_PRIVATE)
                .edit()
                .putString("course_code", code)
                .apply();
    }

    public static String getSchoolName(Context context) {
        return context.getSharedPreferences("ding_state", Context.MODE_PRIVATE)
                .getString("school", "");
    }

    public static void setSchoolName(Context context, String  school) {
        context.getSharedPreferences("ding_state", Context.MODE_PRIVATE)
                .edit()
                .putString("school", school)
                .apply();
    }

    //获取是否进行自动部署设置
    public static int getAutoSettingsFlag(Context context) {
        return context.getSharedPreferences("access_setting", Context.MODE_PRIVATE)
                .getInt("auto_setting_flag", 0);
    }

    public static void setAutoSettingsFlag(Context context, int flag) {
        context.getSharedPreferences("access_setting", Context.MODE_PRIVATE)
                .edit()
                .putInt("auto_setting_flag", flag)
                .apply();
    }

    public static int getAutoSettingStart(Context context) {
        return context.getSharedPreferences("access_setting", Context.MODE_PRIVATE)
                .getInt("auto_setting_start", 0);
    }

    public static void setAutoSettingsStart(Context context, int flag) {
        context.getSharedPreferences("access_setting", Context.MODE_PRIVATE)
                .edit()
                .putInt("auto_setting_start", flag)
                .apply();
    }


    /**
     * MD5 生成
     */
    private static final char[] hexCode = "0123456789ABCDEF".toCharArray();

    public static String md5(String input) throws NoSuchAlgorithmException {
        byte[] bytes = MessageDigest.getInstance("MD5").digest(input.getBytes());
        return printHexBinary(bytes);
    }

    public static String printHexBinary(byte[] data) {
        StringBuilder r = new StringBuilder(data.length * 2);
        for (byte b : data) {
            r.append(hexCode[(b >> 4) & 0xF]);
            r.append(hexCode[(b & 0xF)]);
        }
        return r.toString();
    }

    public static String getActivityPwd(Context context){
        String data = AppUtil.getDeviceUUID(context) + "19950601";
        try {
            return md5(data).substring(0, 6);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getCancelPwd(Context context){
        String data = AppUtil.getDeviceUUID(context) + "19950404";
        try {
            return md5(data).substring(0, 6);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void hideInput(Activity context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE);
        View v = context.getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    //关闭无障碍服务
    public static void autoCloseAccessibilityService(Context context){
        if (isStartAccessibilityServiceEnable(context)) {
            String enabledServicesSetting = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            ComponentName selfComponentName = new ComponentName(context.getPackageName(), MyAccessibilityService.class.getCanonicalName());
            String flattenToString = selfComponentName.flattenToString();
            enabledServicesSetting=enabledServicesSetting.replace(":"+flattenToString , "");

            Settings.Secure.putString(context.getContentResolver(),Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,enabledServicesSetting);
            //Settings.Secure.putInt(context.getContentResolver(),Settings.Secure.ACCESSIBILITY_ENABLED, 0);
            Log.d("yanjun", "autoCloseAccessibilityService: SETTING ACCESSIBILITY SUCCESS!");
        }
        return;
    }

    //开启无障碍服务
    public static void autoOpenAccessibilityService(Context context){
        if (!isStartAccessibilityServiceEnable(context)) {
            String enabledServicesSetting = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            ComponentName selfComponentName = new ComponentName(context.getPackageName(), MyAccessibilityService.class.getCanonicalName());
            String flattenToString = selfComponentName.flattenToString();
            if (enabledServicesSetting==null||
                    !enabledServicesSetting.contains(flattenToString)) {
                enabledServicesSetting += ":"+flattenToString;
            }
            Settings.Secure.putString(context.getContentResolver(),Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,enabledServicesSetting);
            Settings.Secure.putInt(context.getContentResolver(),Settings.Secure.ACCESSIBILITY_ENABLED, 1);
            Log.d("yanjun", "autoOpenAccessibilityService: SETTING ACCESSIBILITY SUCCESS!");
        }
        return;
    }

    /**
     * 判断无障碍服务是否开启
     *
     * @param context
     * @return
     */
    public static boolean isStartAccessibilityServiceEnable(Context context) {
        AccessibilityManager accessibilityManager = (AccessibilityManager)context.getSystemService(Context.ACCESSIBILITY_SERVICE);
        assert accessibilityManager != null;
        List<AccessibilityServiceInfo> accessibilityServices = accessibilityManager.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
        for (AccessibilityServiceInfo info : accessibilityServices) {
            if (info.getId().contains(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    public static void startInstallPermissionSettingActivity(Activity activity) {
        if (activity == null) {
            return;
        }

        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 26) {
            intent.setAction(android.provider.Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
            intent.setData(Uri.fromParts("package", activity.getPackageName(), null));
        } else {
            intent.setAction(android.provider.Settings.ACTION_SECURITY_SETTINGS);
        }

        activity.startActivity(intent);
    }

    public static void startInstallPermissionSettingActivityDing(Activity activity) {
        if (activity == null) {
            return;
        }

        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 26) {
            intent.setAction(android.provider.Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
            intent.setData(Uri.fromParts("package", "com.alibaba.android.rimet", null));
        } else {
            intent.setAction(android.provider.Settings.ACTION_SECURITY_SETTINGS);
        }

        activity.startActivity(intent);
    }

    public static boolean isAppInstalled(Context context,String pkgName) {
        if (pkgName== null || pkgName.isEmpty()) {
            return false;
        }
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(pkgName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        if(packageInfo == null) {
            return false;
        } else {
            return true;//true为安装了，false为未安装
        }
    }

    /**
     * 调用第三方浏览器打开
     * @param context
     * @param url 要浏览的资源地址
     */
    public static  void openBrowser(Context context,String url){
        final Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        // 注意此处的判断intent.resolveActivity()可以返回显示该Intent的Activity对应的组件名
        // 官方解释 : Name of the component implementing an activity that can display the intent
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            final ComponentName componentName = intent.resolveActivity(context.getPackageManager());
            // 打印Log   ComponentName到底是什么
            Log.d("yanjun","componentName = " + componentName.getClassName());
            context.startActivity(Intent.createChooser(intent, "请选择浏览器"));
        } else {
            Toast.makeText(context.getApplicationContext(), "请下载浏览器", Toast.LENGTH_SHORT).show();
        }
    }

    public static void sleep(long millis){
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static boolean isPlay(Context context) {
        AudioManager audioManager = (AudioManager) context.getSystemService(AUDIO_SERVICE);
        return audioManager.isMusicActive();
    }
}
